package com.geeaks.learn.zxing;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.util.Map;
import javax.imageio.ImageIO;
import com.google.common.collect.Maps;
import com.google.zxing.Binarizer;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;

/**
 * @Description: 二维码识别（图片）
 * @author gaoxiang
 * @date 2019-03-15 17:48:44
 */
public class QRCodeTools {
	
	/**
	 * @Description: 图片的字节数组识别出二维码
	 * @author gaoxiang
	 * @date 2019-03-15 17:49:39
	 */
	public static String deEncodeByBase64(byte[] picBytes) throws Exception {
		// byte[] 转BufferedImage
		ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(picBytes);
		LuminanceSource source = new BufferedImageLuminanceSource(ImageIO.read(byteArrayInputStream));
		Binarizer binarizer = new HybridBinarizer(source);
		BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
		Map<DecodeHintType, Object> hints = Maps.newHashMap();
		hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
		Result result = new MultiFormatReader().decode(binaryBitmap, hints);// 解码
		return result.getText();
	}
	
	/**
	 * 解析二维码,此方法解析一个路径的二维码图片
	 * path:图片路径
	 */
	public static String deEncodeByPath(String path) throws Exception {
		LuminanceSource source = new BufferedImageLuminanceSource(ImageIO.read(new File(path)));
		Binarizer binarizer = new HybridBinarizer(source);
		BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
		Map<DecodeHintType, Object> hints = Maps.newHashMap();
		hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
		Result result = new MultiFormatReader().decode(binaryBitmap, hints);// 解码
		return result.getText();
	}
}
